package com.molyfun.parents.im;

import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.listactivity.ListActivity;
import com.molyfun.parents.im.chatrow.BaseChatRow;
import com.molyfun.parents.im.model.BaseMessageEntity;
import com.molyfun.parents.im.model.ChatMessageEntity;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.QiniuSDK;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.CustomMsglistResponse;
import com.molyfun.parents.rest.bean.CustomPlanlistResponse;
import com.molyfun.parents.rest.bean.StringResponse;
import com.molyfun.parents.rest.bean.UploadUrlRequest;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.AndroidBug5497Workaround;
import com.molyfun.parents.utils.FileUtils;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.Tools;
import com.molyfun.parents.view.RecordView.VoiceRecorderView;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.ext.message.TIMConversationExt;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import mabeijianxi.camera.VCamera;
import mabeijianxi.camera.util.Log;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:09/10/2017.
 */

public class BaseChatActivity extends IBaseChatActivity implements View.OnClickListener, UIEventListener, BaseChatRow.MsgResendCallback, MyTIMMsgListener.ITIMMsgReceivedCallback {
    protected static final String TAG = "EaseChatFragment";
    protected static final int REQUEST_CODE_MAP = 1;
    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;

    /**
     * params to fragment
     */
    protected int chatType;
    protected ChatMessageList messageList;
    protected EaseChatInputMenu inputMenu;

    protected EMConversation conversation;

    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;

    private LinearLayout title_material_bar;

    protected Handler handler = new Handler();
    protected File cameraFile;
    protected VoiceRecorderView voiceRecorderView;
    protected SwipeRefreshLayout swipeRefreshLayout;
    protected ListView listView;

    protected ImageView mBackBtn;

//    protected TextView mMarranging;

    protected TextView mDocNum;

    protected boolean haveMoreData = true;
    protected int pagesize = 20;

    protected int[] itemStrings = {R.string.attach_take_pic, R.string.attach_picture, R.string.attach_video};
    protected int[] itemdrawables = {R.drawable.chat_takepic_selector, R.drawable.chat_image_selector,
            R.drawable.chat_video_selector};
    static final int ITEM_TAKE_PICTURE = 1;
    static final int ITEM_PICTURE = 2;
    static final int ITEM_VIDEO = 3;
    protected int[] itemIds = {ITEM_TAKE_PICTURE, ITEM_PICTURE, ITEM_VIDEO};
    private boolean isMessageListInited;
    protected MyItemClickListener extendMenuItemClickListener;
    protected boolean isRoaming = false;

    protected CustomPlanlistResponse.PlanListBean mPlanListBean;
    protected String mGroupId;
    MyConnectionListener myConnectionListener;
    private String TAGS = "BaseChatActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_chat);
        AndroidBug5497Workaround.assistActivity(this);
        getSupportActionBar().setTitle("");

        // userId you are chat with or group id

        initVideoConfig();
        super.onCreate(savedInstanceState);
        Log.i(TAGS, "onCreat()");
        loadMoreLocalMessage();
//        EMClient.getInstance().chatManager().addMessageListener(this);
        myConnectionListener = new MyConnectionListener(this);
//        EMClient.getInstance().addConnectionListener(myConnectionListener);
        TIMManager.getInstance().getUserConfig().setUserStatusListener(myConnectionListener);

        MyTIMMsgListener.addITIMMsgReceivedCallback(this);
    }

    @Override
    public void onMessage(BaseMessageEntity messageEntity) {

        switch (messageEntity.getEventtype()) {
            case MyTIMMsgListener.EventType.CUSTOMPLAN:
                if (messageEntity.getOpertype().equals(MyTIMMsgListener.OperType.GROUPMSG)) {
                    ChatMessageEntity chatMessageEntity = GsonUtil.fromJson(messageEntity.getData(), ChatMessageEntity.class);
                    if (chatMessageEntity.getImgroupid().equals(mPlanListBean.getImgroupid())) {
                        //TODO 转模型
                        Tools.decode(chatMessageEntity);
                        messageList.addData(chatMessageEntity);
                    }
                }
                break;
        }

    }


    /*清除未读消息数*/
    private void clearUnreadCount() {
        TIMConversation conversation = TIMManager.getInstance().getConversation(TIMConversationType.Group, mGroupId);
        if (conversation != null) {
            TIMConversationExt conversationExt = new TIMConversationExt(conversation);
            conversationExt.setReadMessage(null, new TIMCallBack() {
                @Override
                public void onError(int i, String s) {
                }

                @Override
                public void onSuccess() {
                }
            });
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        clearUnreadCount();
    }

    private void initVideoConfig() {
        VCamera.setVideoCachePath(FileUtils.VIDEOPATH);
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍摄SDK，必须
        VCamera.initialize(BaseChatActivity.this);
    }

    /**
     * init view
     */
    protected void initView() {
        // hold to record voice
        //noinspection ConstantConditions
        voiceRecorderView = (VoiceRecorderView) findViewById(R.id.voice_recorder);
        title_material_bar = (LinearLayout) findViewById(R.id.title_material_bar);
        mBackBtn = (ImageView) findViewById(R.id.base_title_left);
        mBackBtn.setOnClickListener(this);
        title_material_bar.setOnClickListener(this);
//        mMarranging = (TextView) findViewById(R.id.arranging);
//        mMarranging.setOnClickListener(this);
        mDocNum = (TextView) findViewById(R.id.doc_num);

        // message list layout
        messageList = (ChatMessageList) findViewById(R.id.message_list);
        messageList.setShowUserNick(true);
//        messageList.setAvatarShape(1);
        listView = messageList.getListView();

        extendMenuItemClickListener = new MyItemClickListener();
        inputMenu = (EaseChatInputMenu) findViewById(R.id.input_menu);
        inputMenu.init();
        inputMenu.setChatInputMenuListener(new EaseChatInputMenu.ChatInputMenuListener() {

            @Override
            public void onSendMessage(final String content) {
                if (!TextUtils.isEmpty(TIMManager.getInstance().getLoginUser())) {
                    sendTextMessage(content);
                } else {

                    Spannable span = EaseSmileUtils.getSmiledText(BaseChatActivity.this, content.replace("[o(]", "[+o(]").replace("[ o(]", "[+o(]"));//txtBody.getMessage());
                    // 设置内容
//                    contentView.setText(span, BufferType.SPANNABLE);
                    inputMenu.getEditText().setText(span, TextView.BufferType.SPANNABLE);

//                    inputMenu.insertText(content);
                    myConnectionListener.showHint(new MyConnectionListener.LoginHxCallback() {
                        @Override
                        public void onSuccess() {
                            sendTextMessage(content);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    inputMenu.getEditText().setText("");
                                }
                            });
                        }
                    });
                }
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {
                //发送大表情
            }

            //            @NeedsPermission(Manifest.permission.RECORD_AUDIO)
            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
//                onRecordBtnPress();

                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new VoiceRecorderView.VoiceRecorderCallback() {

                    @Override
                    public void onVoiceRecordComplete(final String voiceFilePath, final int voiceTimeLength) {

                        if (!TextUtils.isEmpty(TIMManager.getInstance().getLoginUser())) {
                            sendVoiceMessage(voiceFilePath, voiceTimeLength);
                        } else {
                            myConnectionListener.showHint(new MyConnectionListener.LoginHxCallback() {
                                @Override
                                public void onSuccess() {
                                    toast("链接成功");
                                    sendVoiceMessage(voiceFilePath, voiceTimeLength);

                                }
                            });
                        }


                    }
                });
            }

            @Override
            public void onArrangingClick() {
                ListActivity.startCustomPlanProductActivity(BaseChatActivity.this, mPlanListBean.getId());
            }
        });
        registerExtendMenuItem();

        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
                R.color.holo_orange_light, R.color.holo_red_light);

        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_CUSTOMEPLANFIEUPLOAD_INFO, this);
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_CHAT_FINISH, this);
        if (!TextUtils.isEmpty(mPlanListBean.getDegree()) && !mPlanListBean.getDegree().equals("-1")) {
            inputMenu.setVisibility(View.GONE);
        }
        getFileCount();

    }

    private void getFileCount() {
        Call<StringResponse> call = MFPApplication.getInstance().getRestClient().getDocNum(mPlanListBean.getId());
        call.enqueue(new Callback<StringResponse>() {
            @Override
            public void onResponse(Call<StringResponse> call, Response<StringResponse> response) {
                if (response.body() != null && response.body() != null && response.body().getCode() == 200) {
                    mDocNum.setText("(" + response.body().getData() + ")");
                }
            }

            @Override
            public void onFailure(Call<StringResponse> call, Throwable t) {
            }
        });
    }


    @Override
    public void handleUIEvent(Message msg) {
        if (msg.what == EventDispatcherEnum.UI_EVENT_CHAT_FINISH) {
            //TODO 隐藏输入框
            String customplanid = (String) msg.obj;
            if (mPlanListBean.getId().equals(customplanid)) {
                inputMenu.setVisibility(View.GONE);
            }
            pageNum = 1;
            messageList.clearData();
            loadMoreLocalMessage();
            mPlanListBean.setDegree(null);
        } else if (msg.what == EventDispatcherEnum.UI_EVENT_CUSTOMEPLANFIEUPLOAD_INFO) {
            getFileCount();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_material_bar:
                CustomPlanFileUploadActivity.startActivity(BaseChatActivity.this, mPlanListBean);
                break;
            case R.id.arranging:
//                ListActivity.startActivity();
                ListActivity.startCustomPlanProductActivity(BaseChatActivity.this, mPlanListBean.getId());
                break;
            case R.id.base_title_left:
                finish();
                break;

        }
    }

    protected void setUpView() {
        onMessageListInit();

        setRefreshLayoutListener();

    }

    protected void onConversationInit() {
//        conversation = EMClient.getInstance().chatManager().getConversation()
        System.out.println("onConversationInit--mConversionId->" + mGroupId);
        conversation = EMClient.getInstance().chatManager().getConversation(mGroupId, EaseCommonUtils.getConversationType(chatType), true);

//        int msgCount = conversation.getUnreadMsgCount();

        conversation.markAllMessagesAsRead();
        EaseUI.getInstance().getNotifier().reset();

    }

    protected void onMessageListInit() {
        messageList.init(mGroupId, chatType, this);
        setListItemClickListener();

        messageList.getListView().setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
//                inputMenu.hideExtendMenuContainer();
                return false;
            }
        });

        isMessageListInited = true;
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new ChatMessageList.MessageListItemListener() {

            @Override
            public void onUserAvatarClick(String username) {
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onAvatarClick(username);
                }
            }

            @Override
            public void onUserAvatarLongClick(String username) {
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onAvatarLongClick(username);
                }
            }

            @Override
            public void onResendClick(final ChatMessageEntity message) {
                new EaseAlertDialog(BaseChatActivity.this, R.string.resend, R.string.confirm_resend, null, new EaseAlertDialog.AlertDialogUser() {
                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (!confirmed) {
                            return;
                        }
                        resendMessage(message);
                    }
                }, true).show();
            }

            @Override
            public boolean onBubbleClick(ChatMessageEntity message) {
                if (chatFragmentHelper == null) {
                    return false;
                }
                return chatFragmentHelper.onMessageBubbleClick(message);
            }

        });
    }

    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (!isRoaming) {
                            loadMoreLocalMessage();
                        }
                    }
                }, 600);
            }
        });
    }

    /**
     * register extend menu, item id need > 3 if you override this method and keep exist item
     */
    protected void registerExtendMenuItem() {
        for (int i = 0; i < itemStrings.length; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], new MyItemClickListener());
        }
    }


    private int pageNum = 1;

    private String mLastMsgId = "";

    public void loadMoreLocalMessage() {

        Call<CustomMsglistResponse> call = MFPApplication.getInstance().getRestClient().getCustomplanMsgList(mPlanListBean.getId(), "", mLastMsgId, pageNum, RestClient.DEFAULT_PAGE_SIZE);
        call.enqueue(new Callback<CustomMsglistResponse>() {
            @Override
            public void onResponse(Call<CustomMsglistResponse> call, Response<CustomMsglistResponse> response) {
                if (response.body() != null && response.body().getData() != null && response.body().getData().size() > 0) {
                    haveMoreData = true;
                    messageList.addDataListHeader(response.body().getData());
                    pageNum++;
                    mLastMsgId = response.body().getData().get(0).getId();
                } else {
                    if (pageNum != 1) {
                        Toast.makeText(BaseChatActivity.this, getResources().getString(R.string.no_more_messages),
                                Toast.LENGTH_SHORT).show();
                    }else{
                        mLastMsgId = "";
                    }
                    haveMoreData = false;
                }
                Log.i(TAGS, "loadMoreLocalMessage()");
//                messageList.refreshSelectLast();
            }

            @Override
            public void onFailure(Call<CustomMsglistResponse> call, Throwable t) {
            }
        });
        if (pageNum == RestClient.DEFAULT_PAGE) {
            messageList.refreshSelectLast();
        }
        swipeRefreshLayout.setRefreshing(false);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isMessageListInited)
            messageList.refresh();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_CHAT_FINISH, this);
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_CUSTOMEPLANFIEUPLOAD_INFO, this);
        MyTIMMsgListener.removeITIMMsgReceivedCallback(this);
        TIMManager.getInstance().getUserConfig().setUserStatusListener(null);
    }

    /**
     * handle the click event for extend menu
     */
    class MyItemClickListener implements EaseChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            switch (itemId) {
                case ITEM_TAKE_PICTURE:
                    takePicture();
                    break;
                case ITEM_PICTURE:
                    choosePicture();
                    break;
                case ITEM_VIDEO:
                    recordVideo();
//                    startActivity(new Intent(getActivity(), VideoRecordActivity.class));
                    break;

                default:
                    break;
            }
        }

    }

    /**
     * input @
     *
     * @param username
     */
    protected void inputAtUsername(String username, boolean autoAddAtSymbol) {

        EaseAtMessageHelper.get().addAtUser(username);
        EaseUser user = EaseUserUtils.getUserInfo(username);
        if (user != null) {
            username = user.getNick();
        }
//        if(autoAddAtSymbol)
//            inputMenu.insertText("@" + username + " ");
//        else
//            inputMenu.insertText(username + " ");
    }


    /**
     * input @
     *
     * @param username
     */
    protected void inputAtUsername(String username) {
        inputAtUsername(username, true);
    }

    //send message
    protected void sendTextMessage(String content) {
        postRecord(content, 4, null, 0);
//        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
//        message.setChatType(EMMessage.ChatType.GroupChat);
//        EMTextMessageBody txtBody = new EMTextMessageBody(content);
//        message.addBody(txtBody);
////        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
//        sendMessage(message);
    }

    @Override
    public void onMessageResendCallback(ChatMessageEntity chatMessageEntity) {
        if (chatMessageEntity != null && chatMessageEntity.getErrorNativeBody() != null) {
            //1:图片 2.视频 3.音频 4.文字 5.套餐  6.评价
            ChatMessageEntity.ErrorNativeBody errorNativeBody = chatMessageEntity.getErrorNativeBody();
            if (errorNativeBody.getType() == 1) {
                sendImageMessage(errorNativeBody.getFilePath());
            } else if (errorNativeBody.getType() == 2) {
                sendVideoMessage(errorNativeBody.getFilePath(), errorNativeBody.getThumbPath(), errorNativeBody.getLength());
            } else if (errorNativeBody.getType() == 3) {
                sendVoiceMessage(errorNativeBody.getFilePath(), errorNativeBody.getLength());
            }
        }
    }

    protected void sendVoiceMessage(final String filePath, final int length) {


        //添加到列表，上传到服务器,列表loading
        MFPApplication.getInstance().getQiniuSDK().uploadFile(filePath, "mfp/voice" + "/voice_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".mp3"
                , new QiniuSDK.OnFileUpLoadCallback() {
                    @Override
                    public void onFileUpload(String url) {
                        //发送到自己服务器
                        postRecord("", 3, url, length);
                    }

                    @Override
                    public void onFileUploadFailed(String path, String UploadPath) {

                    }

                });
    }

    protected void sendImageMessage(final String imagePath) {
        if (!TextUtils.isEmpty(TIMManager.getInstance().getLoginUser())) {
            postRecord("", 1, imagePath, 0);
        } else {
            myConnectionListener.showHint(new MyConnectionListener.LoginHxCallback() {
                @Override
                public void onSuccess() {
                    toast("链接成功");
                    postRecord("", 1, imagePath, 0);
//                    sendTextMessage(content);
//                    inputMenu.getEditText().setText("");

                }
            });
        }


//        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
//        message.setChatType(EMMessage.ChatType.GroupChat);
//        EMImageMessageBody txtBody = new EMImageMessageBody(new File(imagePath));
//        message.addBody(txtBody);
//
////        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
//        sendMessage(message);
    }

    protected void sendVideoMessage(final String videoPath, final String thumbPath, final int videoLength) {

        if (!TextUtils.isEmpty(TIMManager.getInstance().getLoginUser())) {
            postRecord("", 2, videoPath, thumbPath, videoLength);
//            postRecord("", 1, imagePath, 0);
        } else {
            myConnectionListener.showHint(new MyConnectionListener.LoginHxCallback() {
                @Override
                public void onSuccess() {
                    toast("链接成功");
                    postRecord("", 2, videoPath, thumbPath, videoLength);
//                    postRecord("", 1, imagePath, 0);
//                    sendTextMessage(content);
//                    inputMenu.getEditText().setText("");

                }
            });
        }
//        EMMessage message = EMMessage.createVideoSendMessage(videoPath, thumbPath, videoLength, toChatUsername);
//        sendMessage(message);
    }

    protected void sendFileMessage(String filePath) {
//        EMMessage message = EMMessage.createFileSendMessage(filePath, toChatUsername);
//        sendMessage(message);
    }


    protected void sendMessage(EMMessage message) {
        if (message == null) {
            return;
        }
        if (chatFragmentHelper != null) {
            //set extension
            chatFragmentHelper.onSetMessageAttributes(message);
        }
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            message.setChatType(EMMessage.ChatType.ChatRoom);
        }
        //send message
        EMClient.getInstance().chatManager().sendMessage(message);
        //refresh ui
        if (isMessageListInited) {
            messageList.refreshSelectLast();
        }
    }


    public void resendMessage(final ChatMessageEntity message) {
        //TODO 重发消息

//        message.setStatus(EMMessage.Status.CREATE);
//        EMClient.getInstance().chatManager().sendMessage(message);
//        messageList.refresh();


    }

    /**
     * hide
     */
    protected void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

//    /**
//     * forward message
//     *
//     * @param forward_msg_id
//     */
//    protected void forwardMessage(String forward_msg_id) {
//        final EMMessage forward_msg = EMClient.getInstance().chatManager().getMessage(forward_msg_id);
//        EMMessage.Type type = forward_msg.getType();
//        switch (type) {
//            case TXT:
//                String content = ((EMTextMessageBody) forward_msg.getBody()).getMessage();
//                sendTextMessage(content);
//                break;
//            case IMAGE:
//                // send image
//                String filePath = ((EMImageMessageBody) forward_msg.getBody()).getLocalUrl();
//                if (filePath != null) {
//                    File file = new File(filePath);
//                    if (!file.exists()) {
//                        // send thumb nail if original image does not exist
//                        filePath = ((EMImageMessageBody) forward_msg.getBody()).thumbnailLocalPath();
//                    }
//                    sendImageMessage(filePath);
//                }
//                break;
//            default:
//                break;
//        }
//
//        if(forward_msg.getChatType() == EMMessage.ChatType.ChatRoom){
//            EMClient.getInstance().chatroomManager().leaveChatRoom(forward_msg.getTo());
//        }
//    }

    protected EaseChatFragmentHelper chatFragmentHelper;

    public void setChatFragmentHelper(EaseChatFragmentHelper chatFragmentHelper) {
        this.chatFragmentHelper = chatFragmentHelper;
    }

    public interface EaseChatFragmentHelper {
        /**
         * set message attribute
         */
        void onSetMessageAttributes(EMMessage message);

        /**
         * enter to chat detail
         */
        void onEnterToChatDetails();

        /**
         * on avatar clicked
         *
         * @param username
         */
        void onAvatarClick(String username);

        /**
         * on avatar long pressed
         *
         * @param username
         */
        void onAvatarLongClick(String username);

        /**
         * on message bubble clicked
         */
        boolean onMessageBubbleClick(ChatMessageEntity message);

    }

    @Override
    public void onVideoUploadSuccess(String cover, String path) {
        sendVideoMessage(path, cover, 0);
    }

    @Override
    protected void onVideoUploadFailed(String localPath, String uploadPath) {
//        super.onVideoUploadFailed(path, UploadPath);

    }

    @Override
    public void onPictureUploadFailed(String path, String UploadPath) {

    }

    @Override
    public void onPictureUploadBegin(String path, String UploadPath) {

    }

    @Override
    public void onPictureUploadSuccess(String localPath, String smallUrl, String originalUrl) {
        sendImageMessage(originalUrl);
    }

    @Override
    public String getAttachmentFolder() {
        return "chat";
    }


    private void postRecord(final String content, final int type, final String url, final int timelen) {
        postRecord(content, type, url, null, timelen);
    }

    /**
     * @param content  文字内容
     * @param type     1:图片 2:视频 3:音频 4:文字
     * @param url      音频、视频路径
     * @param coverUrl 视频cover url
     * @param timelen  时长
     *                 <p>
     *                 <p>
     *                 //     * @param content 内容
     *                 //     * @param customplanid 咨询计划id
     *                 //     * @param type 类型 1:图片 2:视频 3:音频 4:文字 5:套餐 6:评价
     *                 //     * @param cover 视频封面
     *                 //     * @param url 链接 套餐消息:套餐url
     *                 //     * @param timelen 时长
     *                 //     * @param extendfield1 扩展字段1 套餐消息:套餐id 评价消息:-1:未操作 1:满意 2:一般 3:不满意
     *                 //     * @param extendfield2 扩展字段2 套餐消息:套餐标题
     *                 //     * @param extendfield3 扩展字段3 套餐消息:套餐原价
     *                 //     * @param extendfield4 扩展字段4 套餐消息:套餐折扣价
     *                 //     * @param extendfield5 扩展字段5 套餐消息:售出数量
     *                 //     * @param extendfield6 扩展字段6 套餐消息:库存
     *                 //     * @return
     */
    private void postRecord(final String content, final int type, final String url, final String coverUrl, final int timelen) {
        if (TextUtils.isEmpty(TIMManager.getInstance().getLoginUser())) {
            myConnectionListener.showHint(new MyConnectionListener.LoginHxCallback() {
                @Override
                public void onSuccess() {
                    postRecord(content, type, url, coverUrl, timelen);
                }
            });
            return;
        }
        if(type == 1 || type == 2 || type == 3){
            UploadUrlRequest uploadUrlRequest = new UploadUrlRequest();
            uploadUrlRequest.setUrl(url);
            Call<StringResponse> call = MFPApplication.getInstance().getRestClient().updateMediaUrl(uploadUrlRequest);
            call.enqueue(new Callback<StringResponse>() {
                @Override
                public void onResponse(Call<StringResponse> call, final Response<StringResponse> response) {

                    Call<BaseResponse> chatCall = MFPApplication.getInstance().getRestClient().addMsg(content, mPlanListBean.getId(), type + "", "", response.body().getData(), timelen + "");
                    final String responseUrlStrBody = response.body().getData();
                    chatCall.enqueue(new Callback<BaseResponse>() {
                        @Override
                        public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                            if (response.body() != null && response.body().getCode() == 200) {
//                    toast("发送成功");
//                                ChatMessageEntity chatMessageEntity = new ChatMessageEntity();
//                                chatMessageEntity.setContent(content);
//                                chatMessageEntity.setType("" + type);
//                                chatMessageEntity.setUrl(responseUrlStrBody);
//                                chatMessageEntity.setCover(coverUrl);
//                                chatMessageEntity.setTimelen("" + timelen);
//                                chatMessageEntity.setCreatedatetime(System.currentTimeMillis());
//                                chatMessageEntity.setUid(MFPApplication.getInstance().getUser().getId());
//                                chatMessageEntity.setUserid(MFPApplication.getInstance().getUser().getId());
//                                chatMessageEntity.setHeadimgurl(MFPApplication.getInstance().getUser().getImgurl());
//                                chatMessageEntity.setId(mPlanListBean.getId());
//                                chatMessageEntity.setConversationId(mPlanListBean.getImgroupid());
//                                messageList.addData(chatMessageEntity);
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        messageList.refreshSelectLast();
//                                    }
//                                });
                            } else {
                                if (response.body() != null) {
                                    toast(response.body().getMsg());
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<BaseResponse> call, Throwable t) {
                            toast("发送失败");
                            if (type == 4) {

                                Spannable span = EaseSmileUtils.getSmiledText(BaseChatActivity.this, content.replace("[o(]", "[+o(]").replace("[ o(]", "[+o(]"));//txtBody.getMessage());
                                // 设置内容
//                    contentView.setText(span, BufferType.SPANNABLE);
                                inputMenu.getEditText().setText(span, TextView.BufferType.SPANNABLE);
                            }
                            dismissProgressDialog();
                        }
                    });


                }

                @Override
                public void onFailure(Call<StringResponse> call, Throwable t) {
                }
            });
        }else{
            Call<BaseResponse> chatCall = MFPApplication.getInstance().getRestClient().addMsg(content, mPlanListBean.getId(), type + "", "", url, timelen + "");
            chatCall.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if (response.body() != null && response.body().getCode() == 200) {
//                    toast("发送成功");
//                        ChatMessageEntity chatMessageEntity = new ChatMessageEntity();
//                        chatMessageEntity.setContent(content);
//                        chatMessageEntity.setType("" + type);
//                        chatMessageEntity.setUrl(url);
//                        chatMessageEntity.setCover(coverUrl);
//                        chatMessageEntity.setTimelen("" + timelen);
//                        chatMessageEntity.setCreatedatetime(System.currentTimeMillis());
//                        chatMessageEntity.setUid(MFPApplication.getInstance().getUser().getId());
//                        chatMessageEntity.setUserid(MFPApplication.getInstance().getUser().getId());
//                        chatMessageEntity.setHeadimgurl(MFPApplication.getInstance().getUser().getImgurl());
//                        chatMessageEntity.setId(mPlanListBean.getId());
//                        chatMessageEntity.setConversationId(mPlanListBean.getImgroupid());
//                        messageList.addData(chatMessageEntity);
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                messageList.refreshSelectLast();
//                            }
//                        });
                    } else {
                        if (response.body() != null) {
                            toast(response.body().getMsg());
                        }
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                    toast("发送失败");
                    if (type == 4) {

                        Spannable span = EaseSmileUtils.getSmiledText(BaseChatActivity.this, content.replace("[o(]", "[+o(]").replace("[ o(]", "[+o(]"));//txtBody.getMessage());
                        // 设置内容
//                    contentView.setText(span, BufferType.SPANNABLE);
                        inputMenu.getEditText().setText(span, TextView.BufferType.SPANNABLE);
                    }
                    dismissProgressDialog();
                }
            });
        }
    }
}
